import React, { Component } from "react";
import Child2 from "../components/Child2";
import Child3 from "../components/Child3";

export default class CTC extends Component {
  constructor() {
    super();
    this.state = {
      list: [
        { id: 1, username: "leson", userage: 18 },
        { id: 2, username: "lulu", userage: 18 },
        { id: 3, username: "lala", userage: 18 },
      ],
    };
  }
  delListById = (id) => {
    //删除的方法
    this.setState({
      list: this.state.list.filter((item) => item.id !== id),
    });
  };
  addListAdd = (item) => {
    let id  =1;
    if(this.state.list.length){//数组有长度
        id  = [...this.state.list].sort((a,b)=>b.id-a.id)[0]["id"]+1;
    }
    if(this.state.list.some(info=>info.username === item.username)){
        alert("该用户名已经存在");
        return false;
    }
    //新增的方法
    this.setState({
      list: [...this.state.list,{...item,id}],
    });
  };
  render() {
    return (
      <div>
        <h3>子传子</h3>
        <hr />
        <Child2 onAdd={this.addListAdd}></Child2>
        <hr />
        <Child3 list={this.state.list} onDelById={this.delListById}></Child3>
      </div>
    );
  }
}
